# -*- coding : utf-8 -*-

import sys

sys.path.append('../')
import json
import requests

import tornado.web
import tornado.ioloop
import tornado.httpserver
import tornado.httpclient
from tornado.options import define
from tornado.options import options

import settings
from credit_voice_service.dialogue.service.dialogue_storage import dialogueStorage

define("port", default=18630, help="run on the given port", type=int)

# 整体打断服务
BREAK_URL = 'http://8.142.85.77:8678/predict?type={}&sessionId={}&query={}'
if ONLINE:
    BREAK_URL = 'http://172.26.2.56:8678/predict?type={}&sessionId={}&query={}'


class BreakHandle(tornado.web.RequestHandler):

    def get(self):
        session_id = self.get_argument('sessionId')
        workspace_id = self.get_argument('workspaceId')
        query = self.get_argument('query')

        dialogueSession = dialogueStorage.get_dialogue_session(session_id, workspace_id)
        conversation_history = dialogueSession.get('conversation_history', list())

        result = self.run(workspace_id, session_id, query, conversation_history)

        self.write(json.dumps(result))

    def run(self, workspace_id, session_id, query, conversation_history):

        url = settings.BREAK_URL.format(workspace_id, session_id, query)
        response = requests.get(url)
        result = json.loads(response.text)
        label = result['label']

        last_skill_name = ''
        for i in range(len(conversation_history) - 1, -1, -1):
            if conversation_history[i]['role'] == 'assistant':
                if conversation_history[i]['sales_skill_name'] == '表明来意':
                    last_skill_name = '表明来意'
                break

        # 表明来意阶段不对非投诉倾向意图进行打断动作
        if last_skill_name == '表明来意' and \
                label not in ['投诉', '别给我打电话了', '你怎么有我号码', '怀疑平台', '怀疑信息泄露', '安全问题', '语音信箱']:
            result['specialBreak'] = True
            result['predict'] = 0
            logger.info('sessionId:{}个性化修改打断结果。'.format(session_id))

        return result


class Handle(tornado.web.RequestHandler):

    # 功能函数
    def run(self):
        pass

    # get请求入口
    def get(self):
        self._get_queries()

    # post请求入口
    def post(self):
        self._post_queries()

    # get请求获取参数
    def _get_queries(self):
        arg_1 = self.get_argument('arg_1', '')
        arg_2 = self.get_argument('arg_2', '')

        return arg_1, arg_2

    # post请求获取灿谁
    def _post_queries(self):
        arg = json.loads(self.request.body)
        arg_1 = arg['arg_1']
        arg_2 = arg['arg_2']

        return arg_1, arg_2


'''if __name__ == '__main__':
    dialogueSession = dialogueStorage.get_dialogue_session('1-2144-0-1749632796958064640-1447', '351')
    conversation_history = dialogueSession.get('conversation_history', list())

    url = 'http://8.142.85.77:8678/predict?type={}&sessionId={}&query={}'.format('351', '1-2144-0-1749632796958064640-1447', '不需要')
    response = requests.get(url)
    result = json.loads(response.text)
    label = result['label']

    last_skill_name = ''
    for i in range(len(conversation_history) - 1, -1, -1):
        if conversation_history[i]['role'] == 'assistant':
            if conversation_history[i]['sales_skill_name'] == '表明来意':
                last_skill_name = '表明来意'
            break

    # 表明来意阶段不对非投诉倾向意图进行打断动作
    if last_skill_name == '表明来意' and \
            label not in ['投诉', '别给我打电话了', '你怎么有我号码', '怀疑平台', '怀疑信息泄露', '安全问题']:
        result['specialBreak'] = True
        result['predict'] = 0

    print(result)

    print(conversation_history)'''

if __name__ == '__main__':
    # 启动服务
    # 2 A100 支持 QPS 10 process
    # 单卡多进程
    # 单次多请求 batch 发送逻辑
    settings.log.info("启动服务...")
    # tornado.options.parse_command_line()
    app = tornado.web.Application(handlers=[
        (r'/original', Handle),
        (r'/dialogue/break/getBreakPredict', BreakHandle),
    ],
        # autoreload=False,
        debug=False,
    )
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.bind(options.port)
    http_server.start(settings.BREAK_PROCESSING_NUM)

    # sockets = tornado.netutil.bind_sockets(settings.PORT)
    # tornado.process.fork_processes(settings.PROCESSING_NUM)
    # http_server.add_sockets(sockets)

    # app.listen(8899)
    settings.log.info("端口：{}...".format(settings.BREAK_PORT))
    tornado.ioloop.IOLoop.instance().start()
